package laos.src;


import java.util.List;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.util.constants.MapViewConstants;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import laos.src.R;

public class AreaSelectorActivity extends Activity implements MapViewConstants,
		LocationListener {
	private static final double DELTA = 0.05;
	private MapView mapView;
	private MapController mapController;
	private MapOverlay mmapOverlay = null;
	private LocationManager mLocMgr;
	private IGeoPoint[] gselected;
	private Rect gamefield;
	private int[] screenSize;
	// private Handler mHandler;
	// Runnable mUpdateResults;
	// ProgressDialog dialog;
	// private OnTouchListener onTchListen;
	// private void updateResultsInUI(){
	// setContentView(R.layout.gamelayout);
	// }

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		screenSize = new int[2];
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.areaselectorlayout);
		mapView = (MapView) this.findViewById(R.id.mapview);
		mapView.setTileSource(TileSourceFactory.MAPNIK);
		mapView.setBuiltInZoomControls(true);
		mapView.setMultiTouchControls(true);
		Button next = (Button) findViewById(R.id.startButton);
		next.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent gameIntent = new Intent(view.getContext(),
						GameActivity.class);
				int[] borders = new int[8];
				for (int i = 0;i<gselected.length;i++) {
					borders[2*i] = gselected[i].getLatitudeE6();
					borders[2*i+1] = gselected[i].getLongitudeE6();
				}
				Bundle extras = getIntent().getExtras();
				gameIntent.putExtra("IS_GAME_OWNER", true);
				gameIntent.putExtra("IP", extras.getString("IP"));
				gameIntent.putExtra("PORT", extras.getString("PORT"));
				gameIntent.putExtra("BORDERS", borders);
				
				startActivityForResult(gameIntent, 0);
			}

		});
		Button psX = (Button) findViewById(R.id.pscaleXButton);
		psX.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				gamefield.left -= screenSize[1]*DELTA;
				gamefield.right += screenSize[1]*DELTA;
				mapView.invalidate();
			}

		});
		Button msX = (Button) findViewById(R.id.mscaleXButton);
		msX.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				gamefield.left += screenSize[1]*DELTA;
				gamefield.right -= screenSize[1]*DELTA;
				mapView.invalidate();
			}

		});
		Button psY = (Button) findViewById(R.id.pscaleYButton);
		psY.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				gamefield.top -= screenSize[0]*DELTA;
				gamefield.bottom += screenSize[0]*DELTA;
				mapView.invalidate();
			}

		});
		Button msY = (Button) findViewById(R.id.mscaleYButton);
		msY.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				gamefield.top += screenSize[0]*DELTA;
				gamefield.bottom -= screenSize[0]*DELTA;
				mapView.invalidate();
			}

		});
		
		// mHandler = new Handler();
		// mUpdateResults = new Runnable() {
		//
		// @Override
		// public void run() {
		// updateResultsInUI();
		//
		// }
		// };
		// onTchListen = new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View view, MotionEvent event) {
		// double x = event.getX();
		// double y = event.getY();
		// EditText ed = (EditText)findViewById(R.id.textBox);
		// ed.setText(String.valueOf(x)+":"+String.valueOf(y));
		// return false;
		// }
		// };

		mapController = mapView.getController();
		mapController.setZoom(15);
		GeoPoint point2 = new GeoPoint(53554070, -2959520);
		mapController.setCenter(point2);
		mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
		mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 100,
				this);
		this.mmapOverlay = new MapOverlay(this);
		List<Overlay> listOfOverlays = mapView.getOverlays();
		listOfOverlays.add(mmapOverlay);
		mapView.invalidate();
	}

	public void onLocationChanged(Location location) {

		int lat = (int) (location.getLatitude() * 1E6);
		int lng = (int) (location.getLongitude() * 1E6);
		GeoPoint gpt = new GeoPoint(lat, lng);
		mapController.setCenter(gpt);
		mapView.invalidate();
	}

	// private static boolean IsQuadrilateral(LinkedList<IGeoPoint> gselected){
	// if(gselected.size() == 4){
	// IGeoPoint p1 = gselected.get(0);
	// IGeoPoint p2 = gselected.get(1);
	// IGeoPoint p3 = gselected.get(2);
	// IGeoPoint p4 = gselected.get(3);
	//
	// }
	// return true;
	// }
	// public void startLongRunningOperation(){
	// Thread t = new Thread(){
	// public void run(){
	// mHandler.post(mUpdateResults);
	// dialog.dismiss();
	// }
	// };
	// t.start();
	// }
	// public void openGameLayout(){
	// dialog = ProgressDialog.show(this, "Progress","wait",true,false);
	// startLongRunningOperation();
	// //setContentView(R.layout.gamelayout);
	//
	// }
	public class MapOverlay extends org.osmdroid.views.overlay.Overlay {
		// private LinkedList<Point> selected;
		
		
		public MapOverlay(Context ctx) {
			super(ctx);
			// selected = new LinkedList<Point>();
			gselected = new IGeoPoint[4];
			gamefield = null;
		}

		@Override
		protected void draw(Canvas pC, MapView pOsmv, boolean shadow) {
			if (shadow)
				return;

//			Paint lp3;
//			lp3 = new Paint();
//			lp3.setColor(Color.BLUE);
//			lp3.setAntiAlias(true);
//			lp3.setStyle(Style.STROKE);
//			lp3.setStrokeWidth(5);
//			lp3.setTextAlign(Paint.Align.LEFT);
//			lp3.setTextSize(12);
			Paint lp1;
			lp1 = new Paint();
			lp1.setColor(Color.BLUE);
			lp1.setAntiAlias(true);
			lp1.setStyle(Style.FILL_AND_STROKE);
			lp1.setStrokeWidth(5);
			lp1.setAlpha(100);
			lp1.setTextAlign(Paint.Align.LEFT);
			lp1.setTextSize(12);
			final Rect viewportRect = new Rect();
			RectF fieldOnMap = new RectF();
			final Projection projection = pOsmv.getProjection();
			viewportRect.set(projection.getScreenRect());
			if (gamefield == null){
				screenSize[0] = pC.getHeight();
				screenSize[1] = pC.getWidth();
				gamefield = new Rect();
				gamefield.top = (int) Math.floor(pC.getHeight()*0.1);
				gamefield.bottom = (int) Math.floor(pC.getHeight()*0.6);
				gamefield.right = (int) Math.floor(pC.getWidth()*0.9);
				gamefield.left = (int) Math.floor(pC.getWidth()*0.1);
			}
			Matrix toMap = new Matrix();
			toMap.setTranslate(viewportRect.left,viewportRect.top );
			toMap.mapRect(fieldOnMap, new RectF(gamefield));
//			fieldOnMap.top = viewportRect.top + gamefield.top;
//			fieldOnMap.bottom = viewportRect.top +gamefield.bottom;
//			fieldOnMap.right = viewportRect.left +gamefield.right;
//			fieldOnMap.left = viewportRect.left +gamefield.left;
			pC.drawRect(fieldOnMap, lp1);
			/*gselected[0] = projection.fromPixels(gamefield.top, gamefield.left);
			gselected[1] = projection.fromPixels(gamefield.top, gamefield.right);
			gselected[2] = projection.fromPixels(gamefield.bottom, gamefield.right);
			gselected[3] = projection.fromPixels(gamefield.bottom, gamefield.left);*/
			gselected[0] = projection.fromPixels(gamefield.top, gamefield.left);
            gselected[1] = projection.fromPixels(gamefield.top, gamefield.right);
            gselected[2] = projection.fromPixels(gamefield.bottom, gamefield.right);
            gselected[3] = projection.fromPixels(gamefield.bottom, gamefield.left);
			/*Iterator<IGeoPoint> git = gselected.iterator();
			if (gselected.size() > 0) {

				git = gselected.iterator();

				IGeoPoint gp1 = git.next();
				android.graphics.Point p1 = projection.toMapPixels(gp1, null);
				android.graphics.Point p2;
				IGeoPoint first = gp1;
				pC.drawPoint(p1.x, p1.y, lp1);
				while (git.hasNext()) {
					IGeoPoint gp2 = git.next();
					p1 = projection.toMapPixels(gp1, null);
					p2 = projection.toMapPixels(gp2, null);
					pC.drawLine(p1.x, p1.y, p2.x, p2.y, lp1);
					if (!git.hasNext() && gselected.size() == 4) {
						gp1 = first;
						p1 = projection.toMapPixels(gp1, null);
						p2 = projection.toMapPixels(gp2, null);
						pC.drawLine(p1.x, p1.y, p2.x, p2.y, lp1);
						break;
					}
					gp1 = gp2;
				}
			}*/
		}

		/*public boolean onSingleTapUp(final MotionEvent e, final MapView mapView) {
			int x = (int) e.getX();
			int y = (int) e.getY();
			EditText ed = (EditText) findViewById(R.id.textBox);
			ed.setText(String.valueOf(x) + ":" + String.valueOf(y));
			if (gselected.size() < 4) {
				IGeoPoint p = mapView.getProjection().fromPixels(
						(int) e.getX(), (int) e.getY());
				gselected.add(p);
				if (gselected.size() == 4) {
					Intent gameIntent = new Intent(mapView.getContext(),
							GameActivity.class);
					int[] borders = new int[8];// {{gselected.get(0),1}};
					Iterator<IGeoPoint> git = gselected.iterator();
					int i = 0;
					for (git = gselected.iterator(); git.hasNext(); i += 2) {
						IGeoPoint gp = git.next();
						borders[i] = gp.getLatitudeE6();
						borders[i + 1] = gp.getLongitudeE6();
					}
					Bundle extras = getIntent().getExtras();
					gameIntent.putExtra("IS_GAME_OWNER", true);
					gameIntent.putExtra("IP", extras.getString("IP"));
					gameIntent.putExtra("PORT", extras.getString("PORT"));
					gameIntent.putExtra("BORDERS", borders);
					startActivity(gameIntent);
					// a.setBorders(borders);
					// dialog.dismiss();
				}
			}
			mapView.invalidate();
			return true;
		}*/

	}

	@Override
	public void onProviderDisabled(String arg0) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

}